import { useState, useEffect, useCallback, useRef } from 'react';
import { WebRTCManager } from '@/services/webrtc';
import { socketManager } from '@/services/socket';
import { ConnectionState, MediaState } from '@/types';
import { getUserId } from '@/utils/helpers';

export interface UseWebRTCReturn {
  // 媒体流
  localStream: MediaStream | null;
  remoteStream: MediaStream | null;
  
  // 连接状态
  isConnected: boolean;
  connectionState: ConnectionState;
  
  // 媒体状态
  mediaState: MediaState;
  
  // 控制方法
  initializeMedia: () => Promise<void>;
  createOffer: () => Promise<void>;
  createAnswer: (offer: RTCSessionDescriptionInit) => Promise<void>;
  addIceCandidate: (candidate: RTCIceCandidateInit) => Promise<void>;
  toggleMute: () => void;
  toggleVideo: () => void;
  hangUp: () => void;
  
  // 状态
  isInitializing: boolean;
  error: string | null;
}

export const useWebRTC = (roomId: string): UseWebRTCReturn => {
  const [localStream, setLocalStream] = useState<MediaStream | null>(null);
  const [remoteStream, setRemoteStream] = useState<MediaStream | null>(null);
  const [isConnected, setIsConnected] = useState(false);
  const [connectionState, setConnectionState] = useState<ConnectionState>({
    isConnected: false,
    connectionState: 'new',
    iceConnectionState: 'new',
  });
  const [mediaState, setMediaState] = useState<MediaState>({
    isVideoEnabled: true,
    isAudioEnabled: true,
    isScreenSharing: false,
  });
  const [isInitializing, setIsInitializing] = useState(false);
  const [error, setError] = useState<string | null>(null);
  
  const webrtcManagerRef = useRef<WebRTCManager | null>(null);
  const userIdRef = useRef<string>(getUserId());

  // 初始化 WebRTC 管理器
  useEffect(() => {
    webrtcManagerRef.current = new WebRTCManager();
    const manager = webrtcManagerRef.current;

    // 设置事件回调
    manager.onLocalStream((stream) => {
      setLocalStream(stream);
    });

    manager.onRemoteStream((stream) => {
      setRemoteStream(stream);
    });

    manager.onConnectionStateChange((state) => {
      setConnectionState(state);
      setIsConnected(state.isConnected);
    });

    manager.onIceCandidate((candidate) => {
      // 发送 ICE 候选者到远程端
      socketManager.sendIceCandidate(
        'remote-user', // 在实际应用中应该是具体的用户ID
        userIdRef.current,
        candidate
      );
    });

    return () => {
      manager.close();
    };
  }, []);

  // 设置 Socket 事件监听
  useEffect(() => {
    const handleOffer = async (data: { from: string; offer: RTCSessionDescriptionInit }) => {
      try {
        await createAnswer(data.offer);
      } catch (error) {
        console.error('处理 Offer 失败:', error);
        setError('连接建立失败');
      }
    };

    const handleAnswer = async (data: { from: string; answer: RTCSessionDescriptionInit }) => {
      try {
        if (webrtcManagerRef.current) {
          await webrtcManagerRef.current.setRemoteAnswer(data.answer);
        }
      } catch (error) {
        console.error('处理 Answer 失败:', error);
        setError('连接建立失败');
      }
    };

    const handleIceCandidate = async (data: { from: string; candidate: RTCIceCandidateInit }) => {
      try {
        if (webrtcManagerRef.current) {
          await webrtcManagerRef.current.addIceCandidate(data.candidate);
        }
      } catch (error) {
        console.error('处理 ICE 候选者失败:', error);
      }
    };

    const handleUserJoined = async (data: { userId: string }) => {
      // 当有新用户加入时，主动发起连接
      if (data.userId !== userIdRef.current) {
        try {
          await createOffer();
        } catch (error) {
          console.error('发起连接失败:', error);
          setError('连接建立失败');
        }
      }
    };

    socketManager.onOffer(handleOffer);
    socketManager.onAnswer(handleAnswer);
    socketManager.onIceCandidate(handleIceCandidate);
    socketManager.onUserJoined(handleUserJoined);

    return () => {
      socketManager.off('offer', handleOffer);
      socketManager.off('answer', handleAnswer);
      socketManager.off('ice-candidate', handleIceCandidate);
      socketManager.off('user-joined', handleUserJoined);
    };
  }, []);

  // 初始化媒体设备
  const initializeMedia = useCallback(async () => {
    if (!webrtcManagerRef.current || isInitializing) return;

    setIsInitializing(true);
    setError(null);

    try {
      const stream = await webrtcManagerRef.current.getUserMedia();
      setMediaState({
        isVideoEnabled: webrtcManagerRef.current.isVideoEnabled(),
        isAudioEnabled: webrtcManagerRef.current.isAudioEnabled(),
        isScreenSharing: false,
      });
    } catch (error: any) {
      console.error('初始化媒体设备失败:', error);
      setError(error.message || '无法访问摄像头或麦克风');
    } finally {
      setIsInitializing(false);
    }
  }, [isInitializing]);

  // 创建 Offer
  const createOffer = useCallback(async () => {
    if (!webrtcManagerRef.current) {
      throw new Error('WebRTC 管理器未初始化');
    }

    try {
      const offer = await webrtcManagerRef.current.createOffer();
      socketManager.sendOffer(
        'remote-user', // 在实际应用中应该是具体的用户ID
        userIdRef.current,
        offer
      );
    } catch (error) {
      console.error('创建 Offer 失败:', error);
      throw error;
    }
  }, []);

  // 创建 Answer
  const createAnswer = useCallback(async (offer: RTCSessionDescriptionInit) => {
    if (!webrtcManagerRef.current) {
      throw new Error('WebRTC 管理器未初始化');
    }

    try {
      const answer = await webrtcManagerRef.current.createAnswer(offer);
      socketManager.sendAnswer(
        'remote-user', // 在实际应用中应该是具体的用户ID
        userIdRef.current,
        answer
      );
    } catch (error) {
      console.error('创建 Answer 失败:', error);
      throw error;
    }
  }, []);

  // 添加 ICE 候选者
  const addIceCandidate = useCallback(async (candidate: RTCIceCandidateInit) => {
    if (!webrtcManagerRef.current) {
      throw new Error('WebRTC 管理器未初始化');
    }

    try {
      await webrtcManagerRef.current.addIceCandidate(candidate);
    } catch (error) {
      console.error('添加 ICE 候选者失败:', error);
      throw error;
    }
  }, []);

  // 切换静音
  const toggleMute = useCallback(() => {
    if (!webrtcManagerRef.current) return;

    const enabled = webrtcManagerRef.current.toggleAudio();
    setMediaState(prev => ({ ...prev, isAudioEnabled: enabled }));
    
    // 通知远程用户音频状态变化
    socketManager.toggleAudio(roomId, userIdRef.current, enabled);
  }, [roomId]);

  // 切换视频
  const toggleVideo = useCallback(() => {
    if (!webrtcManagerRef.current) return;

    const enabled = webrtcManagerRef.current.toggleVideo();
    setMediaState(prev => ({ ...prev, isVideoEnabled: enabled }));
    
    // 通知远程用户视频状态变化
    socketManager.toggleVideo(roomId, userIdRef.current, enabled);
  }, [roomId]);

  // 挂断通话
  const hangUp = useCallback(() => {
    if (webrtcManagerRef.current) {
      webrtcManagerRef.current.close();
    }
    
    // 离开房间
    socketManager.leaveRoom(roomId, userIdRef.current);
    
    // 重置状态
    setLocalStream(null);
    setRemoteStream(null);
    setIsConnected(false);
    setConnectionState({
      isConnected: false,
      connectionState: 'closed',
      iceConnectionState: 'closed',
    });
    setMediaState({
      isVideoEnabled: true,
      isAudioEnabled: true,
      isScreenSharing: false,
    });
  }, [roomId]);

  return {
    localStream,
    remoteStream,
    isConnected,
    connectionState,
    mediaState,
    initializeMedia,
    createOffer,
    createAnswer,
    addIceCandidate,
    toggleMute,
    toggleVideo,
    hangUp,
    isInitializing,
    error,
  };
};